package com.jjb.www.http.httputil;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;

import androidx.lifecycle.LifecycleOwner;

import com.google.gson.Gson;
import com.hjq.gson.factory.GsonFactory;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnDownloadListener;
import com.hjq.http.model.HttpMethod;
import com.hjq.permissions.Permission;
import com.hjq.toast.ToastUtils;
import com.jjb.www.aop.CheckNet;
import com.jjb.www.aop.Permissions;
import com.tencent.smtt.sdk.QbSdk;

import java.io.File;
import java.util.HashMap;
import java.util.Objects;

/**
 * Author: crg
 * time:   2023/9/28 8:52
 * des:    网络请求下载工具类
 */
public class HttpUtis {


    /**
     * 下载文件
     */
    @CheckNet
    @Permissions({Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE})
    public static void downLoad(Activity context, LifecycleOwner lifecycleOwner, String url) {
        String str;
         Gson gson = GsonFactory.getSingletonGson();
        if (url.contains("?")) {
            str = url.substring(url.lastIndexOf("/") + 1, url.indexOf("?"));
        } else {
            str = url.substring(url.lastIndexOf("/") + 1);
        }

        File externalFileRootDir = context.getExternalFilesDir(null);
        do {
            externalFileRootDir = Objects.requireNonNull(externalFileRootDir).getParentFile();
        } while (Objects.requireNonNull(externalFileRootDir).getAbsolutePath().contains("/Android"));

        String saveDir = Objects.requireNonNull(externalFileRootDir).getAbsolutePath();
        String savePath = saveDir + "/" + Environment.DIRECTORY_DCIM + "/" + "img";
        EasyHttp.download(lifecycleOwner)
                //Environment.getExternalStorageDirectory()
                .method(HttpMethod.GET)
                .file(new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), str))
                .url(url)
                .listener(new OnDownloadListener() {

                    @Override
                    public void onStart(File file) {

                    }

                    @Override
                    public void onProgress(File file, int progress) {

                    }

                    @Override
                    public void onComplete(File file) {
                        ToastUtils.show("下载完成：" + file.getPath());
                        // SDCard地址 /storage/emulated/0
                        // getExternalStorageDirectory在29已废弃
//        String saveDir = Environment.getExternalStorageDirectory().getAbsolutePath();
                        // getExternalFilesDir()  用于获取SDCard/Android/data/你的应用的包名/files/ 目录
//                        String saveDir = Objects.requireNonNull(externalFileRootDir).getAbsolutePath();
//                        String savePath = saveDir + "/" + Environment.DIRECTORY_DCIM + "/" + filename;

                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+file)));
                    }

                    @Override
                    public void onError(File file, Exception e) {
                        ToastUtils.show("下载出错：" + e.getMessage());
                    }

                    @Override
                    public void onEnd(File file) {
                        HashMap<String, String> params = new HashMap<>();
                        params.put("style", "1");
                        params.put("local", "true");
                        String path = file.getAbsolutePath();
//                        QbSdk.canOpenFile(context,path,s->{});
                        QbSdk.openFileReader(context, path, params, s -> { });
                    }

                }).start();
    }
}
